package com.eunion.web.cms.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eunion.common.util.CommUtils;
import com.eunion.core.ExcelUtil;
import com.eunion.core.LogUtil;
import com.eunion.core.common.DeleteVo;
import com.eunion.core.common.JsonVo;
import com.eunion.core.exception.ValidateException;
import com.eunion.fileserver.upload.FileInfo;
import com.eunion.web.cms.entity.Major;
import com.eunion.web.cms.entity.spec.MajorSpec;
import com.eunion.web.cms.service.MajorService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;
import com.eunion.web.common.vo.Web;

/**
 * 专业
 */
@Controller
@RequestMapping("/api/majors")
@PreAuthorize("hasAuthority('major:admin:major')")
public class MajorResource extends BaseTableCommonController<Major, Long> {

    @Override
    protected BaseService<Major, Long> getBaseService() {
        return majorService;
    }

    @Autowired
    private MajorService majorService;

    /**
     * 进入专业页面
     * 
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/major/major";
    }

    /**
     * 专业信息导入
     * 
     * @param obj
     * @param result
     * @param model
     * @param request
     * @return
     */
    @PreAuthorize("hasAuthority('major:import')")
    @PostMapping("/importData")
    public String importData(FileInfo obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            checkBindResult(result);
            if (StringUtils.isNotBlank(obj.getFilepath())) {
                String filepath = obj.getFilepath();
                String fileType = filepath.substring(filepath.lastIndexOf(".") + 1);
                InputStream in = null;

                Workbook wb = null;
                if (fileType.equals("xls")) {
                    in = new FileInputStream(filepath);
                    wb = new HSSFWorkbook(in);
                } else if (fileType.equals("xlsx")) {
                    in = new FileInputStream(filepath);
                    wb = new XSSFWorkbook(in);
                } else {
                    setModuleStatusError(model, "文件格式错误");
                    setModuleImport(model);
                    return getUrlBase().concat("-import");
                }
                String fileNameOrg = obj.getFileNameOrg();

                // 开始解析数据
                Sheet sheet = wb.getSheetAt(0);
                if (fileNameOrg.contains("专业相关信息")) {
                    int totalRows = sheet.getPhysicalNumberOfRows();
                    for(Row row : sheet) {
                       if(row != null) {
                          Major major =  ExcelUtil.readMajorAbortInfos(row);
                          List<Major> fromDB = majorService.findAll(MajorSpec.build(major,true));
                          if(!CommUtils.isEmpty(fromDB)) {
                              Major toDb = fromDB.get(0);
                              toDb.setLearnYear(major.getLearnYear());
                              toDb.setMajorInfo(major.getMajorInfo());
                              toDb.setRaiseRequire(major.getRaiseRequire());
                              toDb.setMainCourse(major.getMainCourse());
                              toDb.setKnowledgeCapacity(major.getKnowledgeCapacity());
                              toDb.setRaiseGoal(major.getRaiseGoal());
                              toDb.setAwardDegree(major.getAwardDegree());
                              majorService.saveAndFlush(toDb);
                          }
                       }
                    }
                } else {
                    List<Major> majorList = ExcelUtil.readMajorByColumn(sheet);
                    // 上传文件的原始名称

                    int majorLevel = 1;
                    if (StringUtils.isNotBlank(fileNameOrg) && fileNameOrg.contains("专科")) {
                        majorLevel = 2;
                    }
                    for (Major cur : majorList) {
                        cur.setMajorLevel(majorLevel);
                    }

                    List<Major> toSave = new ArrayList<>();
                    List<Major> toUpdate = new ArrayList<>();
                    if (majorService.count() > 0) {
                        for (Major element : majorList) {
                            List<Major> find = majorService.findAll(MajorSpec.build(element, true));
                            if (CommUtils.isEmpty(find)) {
                                toSave.add(element);
                            } else {
                                if (find.size() == 1) {
                                    element.setId(find.get(0).getId());
                                    toUpdate.add(element);
                                } else {
                                    majorService.delete(find);
                                    toSave.add(element);
                                }
                            }
                        }
                    }

                    for (Major update : toUpdate) {
                        majorService.saveAndFlush(update);
                    }

                    List<Major> resultList = getBaseService().save(toSave);
                    if (!CommUtils.isEmpty(toSave) && (null == resultList || resultList.size() < 1)) {
                        LogUtil.get(this.getClass()).error("save majorList failed");
                        setModuleStatusOK(model, "导入失败");
                    } else {
                        setModuleStatusOK(model, "导入成功");
                    }
                }
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "导入失败");
        }
        setModuleImport(model);
        return getUrlBase().concat("-import");
    }

    /**
     * 添加。
     */
    @PreAuthorize("hasAuthority('major:add')")
    @PostMapping("/addMajor")
    @ResponseBody
    public JsonVo save(@RequestBody Major obj, BindingResult result) {
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    if (StringUtils.isNotEmpty(error.getDefaultMessage())) {
                        throw new ValidateException(error.getDefaultMessage());
                    }
                }
            }

            // 对专业分类代码校验唯一性。
            Major queryBean = new Major();
            queryBean.setMajorCode(obj.getMajorCode());
            List<Major> list = majorService.findAll(MajorSpec.build(queryBean));
            if (list != null && list.size() > 0) {
                String msg = "专业代码重复，请检查！";
                return new JsonVo(false, msg);
            } else {
                getBaseService().save(obj);
                return new JsonVo(true);
            }
        } catch (ValidateException ve) {
            return new JsonVo(false, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            return new JsonVo(false, "添加失败！");
        }
    }

    /**
     * 修改。
     */
    @PreAuthorize("hasAuthority('major:update')")
    @PostMapping("/updateMajor")
    @ResponseBody
    public JsonVo update(@RequestBody Major obj, BindingResult result) {
        try {
            getBaseService().save(obj);
            return new JsonVo(true);
        } catch (Exception e) {
            LOG.error("update Major error : {}", e);
            return new JsonVo(false, "修改失败！");
        }
    }

    /**
     * 根据传入的数据ids,来删除对象.
     */
    @PostMapping(value = Web.URL_SEP_REMOVE)
    @ResponseBody
    protected JsonVo remove(@RequestBody DeleteVo<Long> dvo) {
        try {
            if (dvo != null && dvo.getIds() != null && dvo.getIds().size() > 0) {
                return super.remove(dvo);
            }
            return new JsonVo(true);
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("remove error ", e);
            return new JsonVo(false, "删除失败");
        }
    }

    @PostMapping(value = "/getMajorByCode")
    @ResponseBody
    public Major getMajorByCode(@RequestBody Major obj, BindingResult result) {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                if (StringUtils.isNotEmpty(error.getDefaultMessage())) {
                    throw new ValidateException(error.getDefaultMessage());
                }
            }
        }

        // 对专业分类代码校验唯一性。
        Major queryBean = new Major();
        queryBean.setMajorCode(obj.getMajorCode());
        List<Major> list = majorService.findAll(MajorSpec.build(queryBean));
        for (Major major : list) {
            if (obj.getMajorCode().equals(major.getMajorCode())) {
                return major;
            }
        }
        return null;
    }

    @PostMapping(value = "/getMajors")
    @ResponseBody
    public List<Major> getMajors(@RequestBody Major obj, BindingResult result) {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                if (StringUtils.isNotEmpty(error.getDefaultMessage())) {
                    throw new ValidateException(error.getDefaultMessage());
                }
            }
        }

        // 对专业分类代码校验唯一性。

        Major queryBean = new Major();
        queryBean.setMajorLevel(obj.getMajorLevel());
        queryBean.setMajorSubject(obj.getMajorSubject());
        queryBean.setMajorClass(obj.getMajorClass());
        return majorService.findAll(MajorSpec.build(queryBean));
    }
}
